package kr.hkit.androidcomplete01.ch08;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class FreelineEx extends Activity {

	private MyView vw;
	ArrayList<Vertex> arVertex;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		vw = new MyView(this);
		setContentView(vw);
		arVertex = new ArrayList<Vertex>();

	}

	// 정점 하나에 대한 정보를 가지는 클래스
	public class Vertex {
		float x;
		float y;
		boolean isDraw;

		public Vertex(float x, float y, boolean isDraw) {
			super();
			this.x = x;
			this.y = y;
			this.isDraw = isDraw;
		}

	}

	protected class MyView extends View {
		Paint mPaint;

		public MyView(Context context) {
			super(context);
			// Paint객체 미리 초기화
			mPaint = new Paint();
			mPaint.setColor(Color.BLACK); // 수정
			mPaint.setStrokeWidth(3);
			mPaint.setAntiAlias(true);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			canvas.drawColor(Color.LTGRAY);

			for (int i = 0; i < arVertex.size(); i++) {
				if (arVertex.get(i).isDraw) {
					canvas.drawLine(arVertex.get(i - 1).x,
							arVertex.get(i - 1).y, arVertex.get(i).x,
							arVertex.get(i).y, mPaint);
				}
			}
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			super.onTouchEvent(event);

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				arVertex.add(new Vertex(event.getX(), event.getY(), false));
				return true;
			}
			if (event.getAction() == MotionEvent.ACTION_MOVE) {
				arVertex.add(new Vertex(event.getX(), event.getY(), true));
				invalidate();
				return true;
			}
			return false;
		}

	}

}
